package com.kaibes.imserver.control;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.Collection;

import com.kaibes.imserver.control.threads.ServerSocketAccept;
import com.kaibes.imserver.model.StartButtonListenerModel;
import com.kaibes.imserver.model.data.HashMapSynchronized;
import com.kaibes.imserver.view.ServerMainView;

public class MainClientControl {

	private int serverPort = 2015;

	private ServerSocket serverSocket;
	// 开启最大并发连接数,消耗资源
	private int maxSameTimeConnect = 1;

	// 服务器允许的最大上线用户数
	private int serverConnectMax = 65535;
	private int serverConnectCur = 0;

	// 单个IP地址允许的最大连接
	private int maxIpConnect = 5;

	private HashMapSynchronized<String, Integer> ipConnects;
	private HashMapSynchronized<String, UserSocketControl> loginSocketControls;
	private HashMapSynchronized<String, UserSocketControl> mainSocketControls;

	public MainClientControl() {
		ipConnects = new HashMapSynchronized<String, Integer>();
		loginSocketControls = new HashMapSynchronized<String, UserSocketControl>();
		mainSocketControls = new HashMapSynchronized<String, UserSocketControl>();
	}

	public void startServer() {

		try {
			serverSocket = new ServerSocket(serverPort);
			ServerMainView.serverPanelView.panel_start
					.addLog("server start ...");

			for (int i = 0; i < maxSameTimeConnect; i++) {
				new Thread(new ServerSocketAccept()).start();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		Thread[] threads = new Thread[Thread.activeCount()];
		Thread.enumerate(threads);
		boolean b = true;
		for (int i = 0; i < threads.length; i++) {
			Thread thread = threads[i];
			if (thread.getName().equals("thread_count")) {
				b = false;
			}
		}
		if (b) {
			new Thread("thread_count") {
				@Override
				public void run() {
					while (StartButtonListenerModel.flag) {
						String log = "=======================================</p><p style='margin-top: 0'>"
								+ "服务器端口是："
								+ serverPort
								+ "</p><p style='margin-top: 0'>"
								+ "服务线程数量："
								+ Thread.activeCount()
								+ "</p><p style='margin-top: 0'>"
								+ "服务器用户数量："
								+ serverConnectCur
								+ "/"
								+ serverConnectMax
								+ "</p><p style='margin-top: 0'>=======================================";
						ServerMainView.serverPanelView.panel_start.addLog(log);
						try {
							sleep(60 * 1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}.start();
		}

	}

	public void closeServer() {
		Collection<UserSocketControl> values_1 = loginSocketControls.values();
		UserSocketControl[] userSocketControlArr_1 = new UserSocketControl[values_1
				.size()];
		values_1.toArray(userSocketControlArr_1);
		for (int i = 0; i < userSocketControlArr_1.length; i++) {
			userSocketControlArr_1[i].getSocketStreamData().closeClient();
		}

		Collection<UserSocketControl> values_2 = mainSocketControls.values();
		UserSocketControl[] userSocketControlArr_2 = new UserSocketControl[values_2
				.size()];
		values_2.toArray(userSocketControlArr_2);
		for (int i = 0; i < userSocketControlArr_2.length; i++) {
			userSocketControlArr_2[i].getSocketStreamData().closeClient();
		}

		try {
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		ServerMainView.serverPanelView.panel_start.addLog(this
				+ ": socket closed");
	}

	public ServerSocket getServerSocket() {
		return serverSocket;
	}

	public int getMaxSameTimeConnect() {
		return maxSameTimeConnect;
	}

	public void setMaxSameTimeConnect(int maxSameTimeConnect) {
		this.maxSameTimeConnect = maxSameTimeConnect;
	}

	public int getServerConnectMax() {
		return serverConnectMax;
	}

	public void setServerConnectMax(int serverConnectMax) {
		this.serverConnectMax = serverConnectMax;
	}

	public int getServerConnectCur() {
		return serverConnectCur;
	}

	public void removeServerConnect() {
		serverConnectCur--;
	}

	public void addServerConnect() {
		serverConnectCur++;
	}

	public int getMaxIpConnect() {
		return maxIpConnect;
	}

	public void addIpconnect(String ip) {
		if (ipConnects.get(ip) == null) {
			ipConnects.put(ip, 1);
		} else {
			ipConnects.replace(ip, ipConnects.get(ip) + 1);
		}
	}

	public void removeIpconnect(String ip) {
		if (ipConnects.get(ip) == 1) {
			ipConnects.remove(ip);
		} else {
			ipConnects.replace(ip, ipConnects.get(ip) - 1);
		}
	}

	public void putLoginSocketControl(String remoteSocketAddress,
			UserSocketControl userLoginControl) {
		loginSocketControls.put(remoteSocketAddress, userLoginControl);
	}

	public void removeLoginSocketControl(String remoteSocketAddress) {
		loginSocketControls.remove(remoteSocketAddress);
	}

	public UserSocketControl getLoginSocketControl(String remoteSocketAddress) {
		return loginSocketControls.get(remoteSocketAddress);
	}

	public void putMainSocketControl(String username,
			UserSocketControl userLoginControl) {
		mainSocketControls.put(username, userLoginControl);
	}

	public void removeMainSocketControl(String username) {
		mainSocketControls.remove(username);
	}

	public UserSocketControl getMainSocketControl(String username) {
		return mainSocketControls.get(username);
	}
	
	public HashMapSynchronized<String, UserSocketControl> getMainSocketControls(){
		return mainSocketControls;
	}

	public void removeClient(String ip) {
		removeServerConnect();
		removeIpconnect(ip);
	}

	// public void addClient(String ip) {
	// addServerConnect();
	// addIpconnect(ip);
	// }

	public boolean isFullConnect() {
		if (serverConnectCur >= serverConnectMax) {
			return true;
		} else {
			return false;
		}
	}

	public boolean isFullIpConnect(String ip) {
		if (ipConnects.get(ip) != null && ipConnects.get(ip) >= maxIpConnect) {
			return true;
		} else {
			return false;
		}
	}

}
